package com.adcc.eoss.efb.ngctrl.util;


import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;

import org.springframework.stereotype.Component;

import java.io.*;

import java.util.ArrayList;
import java.util.List;

@Component
public class CmdRunner {



    public String runCmd(CommandLine cmdLine) throws IOException {
        return runCmd(cmdLine,null);
    }

    public String runCmd(CommandLine cmdLine,File dir) throws IOException {
        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(baos, baos));
        if(dir != null) executor.setWorkingDirectory(dir);
        int exitValue = executor.execute(cmdLine);
        return baos.toString().trim();
    }



    public List<String> runPipeCmd(String cmd) throws IOException {
        Runtime run = Runtime.getRuntime();
        Process process = run.exec(new String[] {"/bin/sh", "-c", cmd});
        InputStream in = process.getInputStream();
        BufferedReader bs = new BufferedReader(new InputStreamReader(in));
        List<String> list = new ArrayList<String>();
        String result = null;
        while ((result = bs.readLine()) != null) {
            list.add(result);
        }
        in.close();
        process.destroy();
        return list;
    }

    public List<String> runPipeCmdErrorOutput(String cmd) throws IOException {
        Runtime run = Runtime.getRuntime();
        Process process = run.exec(new String[] {"/bin/sh", "-c", cmd});
        InputStream in = process.getErrorStream();
        BufferedReader bs = new BufferedReader(new InputStreamReader(in));
        List<String> list = new ArrayList<String>();
        String result = null;
        while ((result = bs.readLine()) != null) {
            list.add(result);
        }
        in.close();
        process.destroy();
        return list;
    }


}
